<template>
  <div class="sumBox">
    <div class="left">
      <el-radio-group v-model="isCollapse" style="margin-bottom: 20px">
        <el-radio-button :value="false">expand</el-radio-button>
        <el-radio-button :value="true">collapse</el-radio-button>
      </el-radio-group>
      <el-menu :default-active="editableTabsValue" class="el-menu-vertical-demo" :collapse="isCollapse">
        <!-- 此处只能使用template 否则el-sub-menu不会隐藏文字 -->
        <template v-for="(v, index) in routers">
          <!-- 无子路由 -->
          <el-menu-item v-if="!v.children" :index="v.path" @click="goToRoute(v)">
            <el-icon>
              <setting />
            </el-icon>
            <template #title>{{ v.name }}</template>
          </el-menu-item>
          <!-- 无子路由结束 -->
          <!-- 有子路由 -->
          <el-sub-menu v-else :index="String(index)">
            <template #title>
              <el-icon>
                <location />
              </el-icon>
              <span>{{ v.name }}</span>
            </template>
            <!-- 其他子菜单项 -->
            <el-menu-item-group v-for="(item, ind) in v.children">
              <el-menu-item :index="v.path + '/' + item.path" @click="goToRoute(v, item)">{{ item.name }}</el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>
          <!-- 有子路由结束 -->
        </template>
      </el-menu>
      <div class="user">
        <el-avatar v-if="userIs" :size="50"
          src="https://cube.elemecdn.com/0/88/03b0d07103f482067139658244046jpeg.jpeg" />
        <span>{{ userIs }}</span>
        <span v-if="userIs" @click="tuichu()">退出</span>
      </div>
    </div>
    <div class="right">
      <el-tabs v-model="editableTabsValue" type="card" class="demo-tabs" closable @tab-remove="removeTab"
        @tab-change="change" row-key="id">
        <el-tab-pane v-for="item in editableTabs" :key="item.content" :label="item.title" :name="item.name">
          <!--router-view  插槽内只有 Component, route   Component当前路由的组件的对象  route路由信息 -->
          <router-view v-slot="{ Component }">
            <keep-alive>
              <component :is="Component" />
            </keep-alive>
          </router-view>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>



<script setup>
/**
 * 
 * 
 * 
 */
import { ref, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import router from './router/index';
import { ElMessage } from 'element-plus'
import Sortable from 'sortablejs'
import { KEYS, set, get } from '@/utils/Storage'
import { useStore } from "vuex";
import store from '@/store';
import {
  Document,
  Menu as IconMenu,
  Location,
  Message,
  Setting,
  Tools,
} from '@element-plus/icons-vue'
import { use } from 'echarts';

function haveCommonValues(array1, array2) {
  // 将数组转换为集合
  const set1 = new Set(array1);
  const set2 = new Set(array2);

  // 检查交集是否为空
  const intersection = new Set([...set1].filter(x => set2.has(x)));

  // 如果交集不为空，则返回true，否则返回false
  return intersection.size > 0;
}
const isCollapse = ref(false)
const routers = ref(router.options.routes.filter(e => e.meta?.isshow != false))
const editableTabsValue = ref('/')
const sto = useStore()
const userIs = ref(sto.state.user)


const editableTabs = ref([
  {
    title: 'home',
    name: '/',
    content: '/',
  }
])
let ky = true;
let t;

// 解决ResizeObserver loop completed with undelivered notifications报错问题
const debounce = (callback, delay) => {
  let tid;
  return function (...args) {
    const ctx = self;
    tid && clearTimeout(tid);
    tid = setTimeout(() => {
      callback.apply(ctx, args);
    }, delay);
  };
};

const _ = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ {
  constructor(callback) {
    callback = debounce(callback, 20);
    super(callback);
  }
};

const route = useRoute()

// 删除当前tab同步左侧菜单栏
watch(route, (newv, oldcurrent) => {
  editableTabsValue.value = newv.fullPath
})

onMounted(() => {
  router.push('/')
  initSortable(); // 在组件挂载后初始化拖拽

})

// 退出登录
const tuichu = () => {
  console.log('111')
  set(KEYS.USER_INFO, '')
  set(KEYS.TOKEN, '')
  set(KEYS.USER_ID, '')

  sessionStorage.removeItem('USER_INFO')
  sessionStorage.removeItem('TOKEN')
  sessionStorage.removeItem('USER_ID')
  window.location.reload()
}

// 跳转
const goToRoute = (onepath, twopath) => {

  if (twopath) {
    // 判断是否登录
    if (userIs.value) {
      router.push(onepath.path + '/' + twopath.path)
      addTab(twopath, onepath)
    } else {
      router.push('lx')
      addTab({ name: '/lx', path: '/lx' })
    }
  } else {
    if (userIs.value) {
      router.push(onepath.path)
      addTab(onepath)
    } else {
      router.push('lx')
      addTab({ name: '/lx', path: '/lx' })
    }
  }
}

// 拖拽
const initSortable = () => {
  const el = document.querySelector('.demo-tabs .el-tabs__nav'); // 找到想要拖拽的那一列
  Sortable.create(el, {
    onEnd: ({ newIndex, oldIndex }) => {
      const [movedItem] = editableTabs.value.splice(oldIndex, 1); // 拖拽后的元素
      editableTabs.value.splice(newIndex, 0, movedItem); // 插入拖拽后的位置
    },
  });
};

const addTab = (targetName, onepath) => {
  const is = editableTabs.value.some(e => e.title === targetName.name)
  if (!is) {
    editableTabs.value.push({
      title: targetName.name,
      name: onepath ? onepath.path + '/' + targetName.path : targetName.path,
      content: onepath ? onepath.path + '/' + targetName.path : targetName.path,
    })
  }
  editableTabsValue.value = onepath ? onepath.path + '/' + targetName.path : targetName.path
}

const change = (e) => {
  const to = editableTabs.value.find(v => v.name === e).content
  router.push(to)
}

const removeTab = (targetName) => {
  // console.log(editableTabs.value)
  if (editableTabs.value.length > 1) {
    const tabs = editableTabs.value
    let activeName = editableTabsValue.value
    if (activeName === targetName) {
      tabs.forEach((tab, index) => {
        if (tab.name === targetName) {
          const nextTab = tabs[index + 1] || tabs[index - 1]
          if (nextTab) {
            activeName = nextTab.name
          }
        }
      })
    }
    // console.log(activeName, 'activeName')
    router.push(activeName)
    editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
  } else {
    if (ky) {
      ElMessage.error('这是最后一个标签页了');
      ky = false;
      if (t) {
        clearTimeout(t);
      }
      t = setTimeout(() => {
        ky = true;
      }, 1000);
    }
  }
}
</script>





<style lang="scss">
* {
  margin: 0;
  padding: 0;
}

::-webkit-scrollbar {
  width: 0px;
  /* 设置滚动条宽度 */
}

.sumBox {
  display: flex;

  .left {
    width: 180px;
    height: 100vh;
    flex-shrink: 0;
    overflow-y: scroll;
    /* background-color: #545c64; */

    .user {
      margin-top: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px
    }
  }

  .right {
    flex: 1;
    height: 100vh;
    width: 100%;
    overflow-y: scroll;
    background-color: #e9eef3;
    position: relative;

    .demo-tabs>.is-top {
      position: fixed;
      width: 100%;
      top: 0;
      z-index: 999;
      background-color: #fff;
    }

    .demo-tabs>.el-tabs__content {
      margin-top: 50px;
    }
  }
}
</style>
